import { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import './social.css'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import zhCN from 'antd/locale/zh_CN';
import { message } from 'antd';
import {
    DatePicker,
    ConfigProvider,
    Input,
    Button,
    Table,
    FloatButton,
    Dropdown,
    Modal,
} from 'antd';
import { SearchOutlined, DownOutlined } from '@ant-design/icons';
dayjs.locale('zh-cn');
const { RangePicker } = DatePicker;

const columns = [
    {
        title: '头像/姓名',
        dataIndex: 'name',
        render: (_, record) => (
            <div style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
            }}>
                <img
                    src={record.img}
                    alt="头像"
                    style={{
                        width: '0.8rem',
                        height: '0.8rem',
                        borderRadius: '50%',
                        marginRight: '0.3rem'
                    }}
                />
                <span>{record.name}</span>
            </div>
        )
    },
    {
        title: 'ID',
        dataIndex: 'userId'
    },
    {
        title: '真实姓名',
        dataIndex: 'realName',
    },
    {
        title: '手机号码',
        dataIndex: 'phone',
    },
    {
        title: '动态数量',
        dataIndex: 'dynamic',
    },
    {
        title: '阅读量',
        dataIndex: 'read',
    },
    {
        title: '关注',
        dataIndex: 'attention',
    },
    {
        title: '粉丝',
        dataIndex: 'fans',
    },
    {
        title: '点赞',
        dataIndex: 'upvote',
    },
    {
        title: '收藏',
        dataIndex: 'collections',
    },
    {
        title: '评论',
        dataIndex: 'comment',
    },
    {
        title: '转发',
        dataIndex: 'transmit',
    },
];

export default function Social() {
    const [list, setList] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [loading, setLoading] = useState(false);
    const [showBackTop, setShowBackTop] = useState(false);
    const timerRef = useRef(null);
    const [isSelectAll, setIsSelectAll] = useState(false);

    // 处理滚动事件
    const handleScroll = (e) => {
        const scrollTop = e.target.scrollTop;

        // 清除之前的定时器
        if (timerRef.current) {
            clearTimeout(timerRef.current);
        }

        // 当滚动到指定高度(300px)时显示按钮
        if (scrollTop > 300) {
            setShowBackTop(true);
        } else {
            // 在顶部附近且不是刚刚点击回到顶部时隐藏按钮
            setShowBackTop(false);
        }
    };

    // 处理回到顶部的点击事件
    const handleBackTop = () => {
        // 点击后立即显示按钮
        setShowBackTop(true);

        // 3秒后隐藏按钮
        timerRef.current = setTimeout(() => {
            setShowBackTop(false);
        }, 3000);
    };

    // 修改表格行选择配置
    const rowSelection = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys) => {
            if (newSelectedRowKeys.length === 0) {
                setIsSelectAll(false);
            }
            setSelectedRowKeys(newSelectedRowKeys);
        },
        preserveSelectedRowKeys: true,
        columnWidth: '60px',
        checkStrictly: false,
        onSelectAll: async (selected) => {
            if (!selected) {
                try {
                    const { data: { code } } = await axios.get("http://localhost:3000/zzj/social/list", {
                        params: { pageSize: 999999 }
                    });

                    if (code === 200) {
                        setSelectedRowKeys([]);
                        setIsSelectAll(false);
                    }
                } catch (error) {
                    console.error('获取数据失败:', error);
                    message.error('操作失败，请重试');
                }
                return;
            }

            try {
                const { data: { code, list: allData } } = await axios.get("http://localhost:3000/zzj/social/list", {
                    params: { pageSize: 999999 }
                });

                if (code === 200 && allData) {
                    const allIds = allData.map(item => item._id);
                    setSelectedRowKeys(allIds);
                    setIsSelectAll(true);
                }
            } catch (error) {
                console.error('获取数据失败:', error);
                message.error('操作失败，请重试');
            }
        }
    };

    // 修改分页配置，添加 total 属性
    const paginationConfig = {
        defaultPageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
        position: ['bottomCenter'],
        showTotal: (total) => `共 ${total} 条数据${isSelectAll ? '，当前已全选' : ''}`,
        total: list.length
    };

    // 修改 handleBatchDelete 函数
    const handleBatchDelete = async (selectedKeys) => {
        if (!selectedKeys?.length) {
            message.warning('请先选择要删除的项');
            return;
        }
        console.log('要删除的ID数组:', selectedKeys); // 检查选中的ID
        try {
            Modal.confirm({
                title: '确认删除',
                content: `确定要删除选中的 ${selectedKeys.length} 项数据吗？此操作不可恢复！`,
                okText: '确认删除',
                cancelText: '取消',
                okButtonProps: {
                    danger: true
                },
                onOk: async () => {
                    try {
                        setLoading(true);
                        
                        // 检查发送的数据格式
                        const postData = { ids: selectedKeys };
                        console.log('发送的数据:', postData);
                        
                        // 检查请求配置
                        const config = {
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        };
                        
                        // 发送删除请求
                        const response = await axios.post(
                            "http://localhost:3000/zzj/social/batchDelete",
                            postData,
                            config
                        );
                        
                        console.log('完整的响应:', response); // 检查完整响应
                        console.log('响应数据:', response.data); // 检查响应数据

                        if (response.data.code === 200) {
                            message.success('删除成功');
                            getList()
                            // 检查删除后的数据
                            const listResponse = await axios.get("http://localhost:3000/zzj/social/list");
                            console.log('删除后的数据列表:', listResponse.data);
                            
                            setList(listResponse.data.list);
                            setSelectedRowKeys([]);
                            setIsSelectAll(false);
                        } else {
                            message.error(response.data.message || '删除失败');
                        }
                    } catch (error) {
                        console.error('删除请求错误:', {
                            message: error.message,
                            response: error.response?.data,
                            status: error.response?.status
                        });
                        message.error('删除失败，请重试');
                    } finally {
                        setLoading(false);
                    }
                }
            });
        } catch (error) {
            console.error('Modal 错误:', error);
            message.error('操作失败，请重试');
        }
    };

    // 修改 getList 函数，添加错误处理
    const getList = async () => {
        try {
            const { data: { code, list: newList } } = await axios.get("http://localhost:3000/zzj/social/list");
            if (code === 200) {
                setList(newList);
            } else {
                message.error('获取数据失败');
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            message.error('获取数据失败，请重试');
        }
    };

    // 修改菜单点击处理函数
    const handleMenuClick = ({ key }) => {
        if (key === '1') {
            handleBatchDelete(selectedRowKeys);
        } else if (key === '2') {
            handleBatchExport(selectedRowKeys);
        }
    };

    // 修改批量导出函数
    const handleBatchExport = async (selectedKeys) => {
        if (!selectedKeys?.length) {
            message.warning('请先选择要导出的项');
            return;
        }

        try {
            setLoading(true);
            message.loading('正在导出数据...', 0);

            // 检查选中的ID
            console.log('开始导出数据，选中的ID:', selectedKeys);

            // 构造请求数据
            const postData = {
                ids: selectedKeys
            };

            // 设置请求配置
            const config = {
                headers: {
                    'Content-Type': 'application/json'
                }
            };

            // 发送导出请求
            const response = await axios.post(
                "http://localhost:3000/zzj/social/batchExport",
                postData,
                {
                    ...config,
                    responseType: 'blob',
                    timeout: 30000
                }
            );

            // 检查响应状态
            if (response.status !== 200) {
                throw new Error('服务器响应错误');
            }

            // 创建下载链接
            const blob = new Blob([response.data], { 
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
            });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            const fileName = `社交数据导出_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
            
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);

            message.destroy();
            message.success('导出成功');
        } catch (error) {
            console.error('导出失败:', error.response || error);
            message.destroy();
            
            // 更详细的错误提示
            if (error.response?.status === 404) {
                message.error('导出接口不存在，请检查服务器配置');
            } else {
                message.error(`导出失败: ${error.response?.data?.message || '请重试'}`);
            }
        } finally {
            setLoading(false);
        }
    };

    // 确保 menuProps 定义在正确位置
    const menuProps = {
        items: [
            {
                key: '1',
                label: '批量删除',
                danger: true,
            },
            {
                key: '2',
                label: '批量导出',
            }
        ],
        onClick: handleMenuClick
    };

    useEffect(() => {
        getList()
    }, [])

    return (
        <>
            <ConfigProvider locale={zhCN}>
                <div className='zzj_social_big_div'>
                    <div
                        className='zzj_social_content_div'
                        id="scrollableDiv"
                        onScroll={handleScroll}
                    >
                        <div className='zzj_social_div_one'>
                            <div className='zzj_social_div_one_top'>
                                <div></div>
                                <span>用户社交统计</span>
                            </div>
                            <div className='zzj_social_div_one_content'>
                                <div className='zzj_social_date_div'>
                                    <span>选择日期</span>
                                    <RangePicker style={{ height: '1rem', width: '9rem' }} />
                                </div>
                                <div style={{ marginLeft: '0.5rem' }}>
                                    <Input placeholder="请输入关键字" style={{ height: '1rem', width: '9rem' }} />
                                </div>
                                <div style={{ marginLeft: '0.5rem' }}>
                                    <Button type="primary" style={{ height: '1rem', width: '1rem' }} shape="circle"
                                        icon={<SearchOutlined style={{ fontSize: '0.5rem' }} />} />
                                </div>
                            </div>
                        </div>

                        <div className='zzj_social_div_two'>
                            <div style={{
                                display: 'flex',
                                justifyContent: 'space-between',
                                marginBottom: '0.5rem',
                                padding: '0 1rem'
                            }}>
                                <span style={{
                                    fontSize: '0.35rem',
                                    color: '#666',
                                    lineHeight: '1rem'
                                }}>
                                    已选择 {selectedRowKeys.length} 项
                                </span>

                                <Dropdown menu={menuProps} placement="bottomRight">
                                    <Button
                                        type="primary"
                                        loading={loading}
                                        style={{
                                            backgroundColor: '#3ed4a7',
                                            borderColor: '#3ed4a7',
                                            height: '1rem',
                                            display: 'flex',
                                            alignItems: 'center',
                                            fontSize: '0.35rem',
                                        }}
                                    >
                                        批量操作 <DownOutlined style={{ fontSize: '0.35rem', marginLeft: '0.2rem' }} />
                                    </Button>
                                </Dropdown>
                            </div>

                            <Table
                                rowSelection={rowSelection}
                                rowKey="_id"
                                columns={columns}
                                dataSource={list}
                                align="center"
                                pagination={paginationConfig}
                                scroll={{ x: true }}
                            />
                            <FloatButton.BackTop
                                target={() => document.getElementById('scrollableDiv')}
                                visibilityHeight={300}
                                onClick={handleBackTop}
                                style={{
                                    display: showBackTop ? 'block' : 'none',
                                    transition: 'all 0.3s'
                                }}
                            />
                        </div>

                        {/* 标注盒子 */}
                        <div className='zzj_social_label_div'>
                            <p>Copyright © DaisyAxure All Rights Reserved</p>
                        </div>
                    </div>
                </div>
            </ConfigProvider>
        </>
    )
}
